package gwtgaetools.client;

import gwtgaetools.client.listeners.Listener;
import gwtgaetools.shared.model.BaseObject;
import gwtgaetools.shared.model.ObjectManager;
import gwtgaetools.shared.model.PropertyEnum;

import java.util.ArrayList;

public class OMList<T extends BaseObject<T, PE>, M extends ObjectManager<T, M, PE>, PE extends PropertyEnum<PE, T>> extends BasicList<M> {

	/**
	 * 
	 */
	private static final long	serialVersionUID	= 1L;

	public OMList() {}

	public OMList(ArrayList<M> i) {
		super(i);
	}

	@Override public boolean add(final M t) {
		boolean b = false;
		if (t.index() != null) {
			int i = findIndex(t);

			super.add(i, t);

			b = true;

			t.index().listeners.add(new Listener<ItemManager<Integer>>() {
				@Override public void observe(ItemManager<Integer> it) {
					updateIndex(t, findIndex(t), indexOf(t));
				}
			});
		} else {
			b = super.add(t);
		}
		t.deleteListeners.add(this);
		return b;
	}

	@Override public void add(int index, M t) {
		super.add(index, t);
		t.deleteListeners.add(this);
	}

	public M getById(String id) {
		for (M t : this) {
			if (t.sameAs(id)) return t;
		}
		return null;
	}

	public int indexOf(M in) {
		for (int i = 0; i < size(); i++) {
			M t = get(i);
			if (t.sameAs(in)) return i;
		}
		return -1;
	}

	private int findIndex(M t) {
		int i = 0;
		boolean passObject = false;
		while (i < size()) {
			if (t.sameAs(get(i))) passObject = true;
			else if (t.index().getItem() < get(i).index().getItem()) break;
			i++;
		}
		if (passObject) i--;
		return i;
	}

}
